package com.fzk.blog.blog.service.impl;

import com.fzk.blog.blog.service.IRedisService;
import com.fzk.blog.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author fzk
 * @date 2021-09-09 10:57
 */
@Service(value = "redisService")
public class RedisService implements IRedisService {
    @Autowired
    @Qualifier(value = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Value("${spring.redis.expire_time}")// 以s为单位哦
    private long expire_time;

    @Override
    public void setEx(String key, String value) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set(key, value, Duration.ofSeconds(expire_time));
    }

    @Override
    public String get(String key) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        return opsForValue.get(key);
    }

    @Override
    public void setEx(String key, String value, long expire) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set(key, value, Duration.ofSeconds(expire));
    }

    @Override
    public String getDel(String key) {
        String str = stringRedisTemplate.opsForValue().get(key);
        stringRedisTemplate.delete(key);
        return str;
    }

    @Override
    public Boolean delete(String... keys) {
        if (keys.length == 1)
            return stringRedisTemplate.delete(keys[0]);
        if (keys.length == 0)
            throw new MyException(500, "keys的长度不能为0");
        else {
            Long delete = stringRedisTemplate.delete(Arrays.asList(keys));
            return delete != null && delete == keys.length;
        }
    }
}
